#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/14 9:14
    Desc  :
--------------------------------------
"""
from common.libs.JsonResponseUtils import JsonResponse
from servers.models.projectModel import Project
from servers.models.userModel import User
from servers.servers.BaseServices import BaseServices
from servers.servers.UserServices import add_valid_user


class ProjectServices(BaseServices):

    def __init__(self, document=Project):
        super().__init__(document)

    def select(self, **kwargs):
        return self.document.objects(**kwargs).all()


def add_valid_project(**kwargs):
    projectName, projectUsername, projectUserphone = \
        kwargs.get("projectName"), kwargs.get("projectUsername"), kwargs.get("projectUserphone")
    if projectName is None or projectName == '':
        return JsonResponse(code = 40007, data = None, message = "projectName不能为空").jsonExit()
    if projectUsername is None or projectUsername == '':
        return JsonResponse(code = 40007, data = None, message = "projectUsername不能为空").jsonExit()
    if projectUserphone is None or projectUserphone == '':
        return JsonResponse(code = 40007, data = None, message = "projectUserphone不能为空").jsonExit()

    project = Project.objects(projectName = projectName)

    if project.count() != 0:
        return JsonResponse(code = 40008, data = None, message = "projectName已存在").jsonExit()

    # add_valid_user(admin = 101, username = projectUsername, phone = projectUserphone)
    is_valid = add_valid_user(admin = 101, username = projectUsername, phone = projectUserphone)
    if is_valid:
        return is_valid
    User(username = projectUsername, phone = projectUserphone, admin = 101, projectList = [projectName]).save()


def organize_add_project(**kwargs):
    """
    机构端新增项目
    :param kwargs:
    :return:
    """

    projectName, projectUsername, projectUserphone = \
        kwargs.get("projectName"), kwargs.get("projectUsername"), kwargs.get("projectUserphone")
    if projectName is None or projectName == '':
        return JsonResponse(code = 40007, data = None, message = "projectName不能为空").jsonExit()
    if projectUsername is None or projectUsername == '':
        return JsonResponse(code = 40007, data = None, message = "projectUsername不能为空").jsonExit()
    if projectUserphone is None or projectUserphone == '':
        return JsonResponse(code = 40007, data = None, message = "projectUserphone不能为空").jsonExit()

    project = Project.objects(projectName = projectName)

    if project.count() != 0:
        return JsonResponse(code = 40008, data = None, message = "projectName已存在").jsonExit()

    return None


def get_project_by_id(id: str):
    """
    通过项目id获取项目独享
    :param id:
    :return:
    """
    project = Project.objects(id = id)
    if project.count() != 0:
        return project.first()
    return None
